<?php

/**
 * The following code blocks deal with incoming results of offsite payments
 */


// allow IPN to notify the gateway that payment has been processed
if(get('ipn')=='1' && get('hash')!=''){
	$hash = preg_replace('/[^a-zA-Z0-9]/', '', get('hash'));
	
	//echo $hash;
	//echo "SELECT * FROM {$this->config['db_prefix']}isubscribe_offsite_payments WHERE hash = '{$hash}'";
	$osData = $DB->fetchRow("SELECT * FROM {$this->config['db_prefix']}isubscribe_offsite_payments WHERE hash = '{$hash}'");
	if(!is_array($osData) || count($osData)==0){
		die($this->Lang('invalid_hash'));
	};
	$DB->update(cms_db_prefix().'isubscribe_offsite_payments', array('ipn_received'=>'1'), "hash = '{$hash}'");
	$priceData = unserialize($osData['price_data']);
	$subData = unserialize($osData['subscription_data']);
	$gwObj = unserialize($CRYPT->decrypt($osData['gateway_object']));
	$gwObj->processIpn();
	$serObj = $CRYPT->crypt(serialize($gwObj));
	$DB->update(cms_db_prefix().'isubscribe_offsite_payments', array('gateway_object'=>$serObj), "hash = '{$hash}'");
	$hookParams = array(
    'price_data' => $priceData,
    'subscription_data' => $subData,
    'gateway_object' => $gwObj
  );
  $newParams = Antz::Hookup('ISubscribe_processIpn', $hookParams);
  exit;
}

// if cancelled an offsite payment
if(get('cancelled')==1 && get('hash')!=''){
	$hash = preg_replace('/[^a-zA-Z0-9]/', '', get('hash'));
	if(!($osData = $DB->fetchRow("SELECT * FROM {$this->config['db_prefix']}isubscribe_offsite_payments WHERE hash = '{$hash}'"))){
		Antz::addError($this->Lang('invalid_link'));
		Antz::goLastPage();
	};
	$priceData = unserialize($osData['price_data']);
	$subData = unserialize($osData['subscription_data']);
	$gwObj = unserialize($CRYPT->decrypt($osData['gateway_object']));
	if(!is_object($gwObj) || !($gwObj instanceof ISubscribe_Payment_Gateway)){
		Antz::addError($this->Lang('unrecognized_gateway'));
		Antz::redir($Antz->addParamsToUrl($Antz->getUrlById($returnid), array('subscription'=>get('subscription'))));
	};
	$content = $gwObj->cancelOffsitePayment();
	$DB->delete(cms_db_prefix().'isubscribe_offsite_payments', "hash = '{$hash}'");
	$hookParams = array(
    'price_data' => $priceData,
    'subscription_data' => $subData,
    'gateway_object' => $gwObj
  );
  $newParams = Antz::Hookup('ISubscribe_cancelled', $hookParams);
	echo $content;
	return;
}

// if returning from an offsite payment, lets check if it was valid and process if true
if(get('completed')==1){
	$hash = preg_replace('/[^a-zA-Z0-9]/', '', get('hash'));
	$osData = $DB->fetchRow("SELECT * FROM {$this->config['db_prefix']}isubscribe_offsite_payments WHERE hash = '{$hash}'");
	if(!is_array($osData) || count($osData)==0){
		Antz::addError($this->Lang('invalid_link'));
		Antz::goLastPage();
	};
	$priceData = unserialize($osData['price_data']);
	$subData = unserialize($osData['subscription_data']);
	
	//var_dump($subData);
	
	$gwObj = unserialize($CRYPT->decrypt($osData['gateway_object']));
	$result = (bool) $gwObj->checkOffsitePayment();
	$DB->delete(cms_db_prefix().'isubscribe_offsite_payments', "hash = '{$hash}'");



	if($result){
		$expireTstamp = $this->AddSubscription($priceData, $subData, $gwObj, $USER->userid);
		if($expireTstamp > 0) Antz::addSuccess($this->Lang('successful_subscription', date('H:ia d M Y', $expireTime)));
	  else Antz::addSuccess($this->Lang('successful_subscription_lifetime'));
	  
    $hookParams = array(
      'price_data' => $priceData,
      'subscription_data' => $subData,
      'gateway_object' => $gwObj,
      'expire_tstamp' => $expireTstamp
    );
    $newParams = Antz::Hookup('ISubscribe_completeSuccess', $hookParams);
       

  }else{
		$errors = $gwObj->getErrorsAsArray();
		$gwObj->resetErrors();
		if(count($errors)>0){
			Antz::addError($this->Lang('there_were_errors'));
			foreach($errors as $errorMessage) Antz::addError($errorMessage);
		}else{
			Antz::addError($this->Lang('invalid_payment_unspecified'));
		};
		$hookParams = array(
      'price_data' => $priceData,
      'subscription_data' => $subData,
      'gateway_object' => $gwObj,
      'errors' => $errors
    );
    $newParams = Antz::Hookup('ISubscribe_completeError', $hookParams);
	};
	Antz::goLastPage();
}

/**
 * end of offsite payment processing
 */


if(!$USER->isLoggedIn()){
	Antz::setLastPage();
	Antz::addSuccess($this->Lang('login_message'));
	Antz::redir($Antz->getUrlById($IUsers->GetConfig('login_id')));
}

$subKey = preg_replace('/[^a-zA-Z0-9\-_]/', '', get('subscription'));

if($DB->countRows(cms_db_prefix().'isubscribe_subscriptions', "keyname = '{$subKey}' AND is_active = 1 AND is_deleted = 0")==0){
	Antz::addError($this->Lang('subscription_unavailabele'));
	Antz::redirect($Antz->getUrlById($this->GetConfig('advertisement_id')));
}

// we have a valid subscription


$subData = $DB->fetchRow("SELECT * FROM {$this->config['db_prefix']}isubscribe_subscriptions WHERE keyname = '{$subKey}'");
$subId = $subData['id'];

$tmpPrices = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}isubscribe_subscription_prices WHERE subscription_id = '{$subId}'");

$prices = array();
foreach($tmpPrices as $k=>$v){
	// check that they are eligible for this price
	if(!$IUsers->isMemberOfGroup($v['group_key'])) continue;
	if(array_key_exists($v['currency_key'], $prices)){
		// lets make sure we give them the most applicable price
		$lowest = (bool) $this->GetConfig('show_lowest_prices');
		if($lowest){
			// show the lower price
			if($prices[$v['currency_key']]['price'] > $v['price']) $prices[$v['currency_key']] = $v;
		}else{
			// show the higher price
			if($prices[$v['currency_key']]['price'] < $v['price']) $prices[$v['currency_key']] = $v;
		}
	}else{
		// lets offer them this price for starters
		$prices[$v['currency_key']] = $v;
	}
}

// now we have one price for each available currency in our $prices array

if(get('payment_method')!=''){
	// have selected a payment method
	$methodId = (int) get('payment_method');
	if($DB->countRows(cms_db_prefix().'isubscribe_payment_gateways', "id = '{$methodId}' AND is_active = 1")==0){
		Antz::addError($this->Lang('invalid_gateway'));
		Antz::redir($Antz->addParamsToUrl($Antz->getUrlById($returnid), array('subscription'=>get('subscription'))));
	};

	$priceId = (int) post('price_id');
  $priceData = $DB->fetchRow("SELECT * FROM {$this->config['db_prefix']}isubscribe_subscription_prices WHERE id = '{$priceId}'");

	if(!is_array($priceData) || count($priceData)==0){
		$error = true;
		Antz::addError($this->Lang('invalid_currency'));
		Antz::redir($Antz->addParamsToUrl($Antz->getUrlById($returnid), array('subscription'=>get('subscription'))));
	};
	$gwData = $DB->fetchRow("SELECT * FROM {$this->config['db_prefix']}isubscribe_payment_gateways WHERE id = '{$methodId}'");
	$gwObj = unserialize($CRYPT->decrypt($gwData['obj']));

	if($gwObj->getMethod()=='offsite'){
		// doing an offsite payment
		$gwObj->setPriceData($priceData);
		$gwObj->setSubscriptionData($subData);

		$this->smarty->assign('priceData', $priceData);
		$this->smarty->assign('subscriptionData', $subData);

		echo $this->ProcessTemplate('purchase-subscription.show-summary.php');

		$hash = md5(rand(0, 99).$priceData['price'].rand(0, 99).$subData['keyname'].rand(0, 99));
		while($DB->countRows(cms_db_prefix().'isubscribe_offsite_payments', "hash = '{$hash}'")>0){
			$hash = md5(rand(0, 99).$priceData['price'].rand(0, 99).$subData['keyname'].rand(0, 99));
		};

		$cancelReturnUrl = $Antz->addParamsToUrl($Antz->getUrlById($returnid), array('cancelled'=>'1', 'subscription'=>get('subscription'), 'hash'=>$hash));
		$completeReturnUrl = $Antz->addParamsToUrl($Antz->getUrlById($returnid), array('completed'=>'1', 'subscription'=>get('subscription'), 'hash'=>$hash));
		$ipnUrl = $Antz->addParamsToUrl($Antz->getUrlById($returnid), array('ipn'=>'1', 'subscription'=>get('subscription'), 'hash'=>$hash));

		$btn = $gwObj->getButton($completeReturnUrl, $cancelReturnUrl, $ipnUrl);

		$dbParams = array(
			'hash' => $hash,
			'user_id' => $USER->userid,
			'price_data' => serialize($priceData),
			'subscription_data' => serialize($subData),
			'gateway_object' => $CRYPT->crypt(serialize($gwObj)),
			'tstamp' => time()
		);
		$DB->insert(cms_db_prefix().'isubscribe_offsite_payments', $dbParams);

		echo $btn;

		return;

	}else if($gwObj->getMethod()=='onsite'){
		// doing an onsite payment
		$gwObj->setPriceData($priceData);
		$gwObj->setSubscriptionData($subData);

		if($gwObj->processOnlinePayment()){
				$expireTime = $this->AddSubscription($priceData, $subData, $gwObj, $USER->userid);
				Antz::addSuccess($this->Lang('successful_subscription', date('H:ia d M Y', $expireTime)));
		}
	}else{
		// invalid object!
		Antz::addError($this->Lang('gateway_unavailable'));
		$DB->update(cms_db_prefix().'isubscribe_payment_gateways', array('is_active'=>0), "id = {$methodId}");
		Antz::redir($Antz->addParamsToUrl($Antz->getUrlById($returnid), array('subscription'=>get('subscription'))));
	};

}else{
	// have to select a payment method and a currency
	$gateways = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}isubscribe_payment_gateways WHERE is_active = 1");

	$curSel = Antz::newObject('Antz_Form_Components_Select', array('price_id', 'Currency', post('price_id', '0')));
	$curSel->add($this->Lang('select_currency'), '0');
	foreach($prices as $k=>$v){
		$curSel->add('$'.number_format($v['price'], 2, '.', ',').' '.$v['currency_key'], $v['id']);
	};
	$curSel->setWrap(false);
	$curSel->showLabel(false);
	$curSel->setId('currency-selector');

	foreach($gateways as $k=>$v){
		$obj = unserialize($CRYPT->decrypt($v['obj']));
		if(!is_object($obj) || !($obj instanceof ISubscribe_Payment_Gateway)){
			unset($gateways[$k]);
			continue;
		};
		$gateways[$k]['purchase_url'] = $Antz->addParamsToUrl(THIS_PAGE_URL, array('payment_method'=>$v['id']));
	};
    
    if(count($prices)==1){
        foreach($prices as $k=>$v) break;
        $this->smarty->assign('defaultPrice', $prices[$k]['price']);
        $this->smarty->assign('defaultPriceId', $prices[$k]['id']);
        $this->smarty->assign('defaultCurrency', $prices[$k]['currency_key']);
    };
    $this->smarty->assign('prices', $prices);
	$this->smarty->assign('currencySelector', $curSel->render());
	$this->smarty->assign('gateways', $gateways);
	$this->smarty->assign('subData', $subData);

	echo $this->ProcessTemplate('purchase-subscription.select-gateway.php');
    /*
    
    foreach($gateways as $k=>$v){
		$obj = unserialize($CRYPT->decrypt($v['obj']));
		if(!is_object($obj) || !($obj instanceof ISubscribe_Payment_Gateway)){
			unset($gateways[$k]);
			continue;
		};
		$gateways[$k]['object'] = $obj;
		$gateways[$k]['purchase_url'] = $Antz->addParamsToUrl(THIS_PAGE_URL, array('payment_method'=>$v['id']));
	};
    
    foreach($gateways as $k=>$v){
        echo '<div class="isubscribe-select-gateway">';
        echo $v['object']->getCurrencySelector($prices, $subData, $v['purchase_url']);
        echo '</div>';
    }
    */
}
